package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.kafka.streams.internals.ApiUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jack
 * @data 2024 19:01
 */

public class ApUserImplClassTest extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * app用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //游客登录
        if (StringUtils.isEmpty(loginDto.getPhone()) &&StringUtils.isEmpty(loginDto.getPassword())){
            String token = AppJwtUtil.getToken(0);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }else {
        //非游客登录
            LambdaQueryWrapper<ApUser> lambdaQueryWrapper = Wrappers.lambdaQuery(ApUser.class).eq(ApUser::getPhone, loginDto.getPhone());
            ApUser apUser = getOne(lambdaQueryWrapper);
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String password = DigestUtils.md5DigestAsHex((apUser.getPassword() + apUser.getSalt()).getBytes(StandardCharsets.UTF_8));

            if (password.equals(apUser.getPassword())){
                Map<String,Object> map = new HashMap<>();
                String token = AppJwtUtil.getToken(apUser.getId());
                map.put("token",token);
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("data",apUser);
                return ResponseResult.okResult(map);

            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
    }
}
